package 数组算法;

import java.util.ArrayList;
import java.util.List;

public class permute46 {
    /**
     * 回溯算法
     *
     * @param nums
     * @return
     */
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> lists = new ArrayList<>();
        if (nums.length == 0) {
            return lists;
        }
        boolean[] vis = new boolean[nums.length];
        dfs(nums, 0, new ArrayList<Integer>(), lists, vis);
        return lists;
    }

    private void dfs(int[] nums, int index, ArrayList<Integer> list, List<List<Integer>> lists, boolean[] vis) {
        if (index == nums.length) {
            if (!lists.contains(list)) {
                lists.add(new ArrayList<>(list));
            }
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (!vis[i]) {
                vis[i] = true;
                list.add(nums[i]);
                dfs(nums, index + 1, list, lists, vis);
                lists.remove(list.size() - 1);
                vis[i] = false;
            }
        }
    }
}
